using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SolarWinds.Helpers;

namespace SolarWinds.Widgets
{
    public abstract class TiledWidget : Widget
    {
        protected String mTileAsset = @"Textures\tiles";
        protected Point mTileSize = new Point(16, 16); //16x16 pixel
        protected Texture2D mTileTexture;

        protected Rectangle[] mSrcRects;
        protected Rectangle[] mDestRects;
        protected Color[] mTileColors;
        
        #region Properties

        public String TileAsset
        {
            get { return mTileAsset; }
            set { mTileAsset = value; }
        }	

        public Point TileSize
        {
            get { return mTileSize; }
            set { mTileSize = value; }
        }

        #endregion

        static int mTileWidgetsCount = 0;

        public TiledWidget(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // lets do some instance counting
            //++mTileWidgetsCount;
        }

        protected internal override void PaintEvent()
        {
            // draw each tile
            for (int i = 0; i < mDestRects.Length; i++)
            {
                SpriteBatch.Draw(mTileTexture, mDestRects[i], mSrcRects[i], mTileColors[i]);
            }
        }

        protected override void LoadContent()
        {
            base.LoadContent();

            mTileTexture = Game.Content.Load<Texture2D>(@mTileAsset);

            InitializeRects();
        }

        protected override void UnloadContent()
        {
            if (mTileTexture != null)
            {
                mTileTexture = null;
            }

            base.UnloadContent();
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            UpdateSrcDestRects();
        }

        protected abstract void InitializeRects();
        protected abstract void UpdateSrcDestRects();

        protected Rectangle TileIndex2Rectangle(Point index)
        {
            return TileHelper.TileIndex2Rectangle(index, mTileSize);
        }
    }
}